//
// Created by Jisam on 01/10/2024 4:49 PM.
// Solution of  a
#include <bits/stdc++.h>

#define  int long long
#define  endl "\n"
using namespace std;


signed main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    int T =1;
    cin >> T;
    while(T --){

        int n,k;
        cin >> n >> k;
        if(k == 1 ){
            cout << n  << endl;
            continue;
        }
        int cnt = 0;
        while(n){
            cnt += n % k;
            n /= k;
        }
        cout << cnt  << endl;
    }
    return 0;
}